import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable
} from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { Role } from 'src/users/enums/role.enum'
import { AuthenticatedRequest } from '../interfaces/request.interface'

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<Role[]>('roles', context.getHandler())
    if (!roles) {
      return true
    }
    const request: AuthenticatedRequest = context.switchToHttp().getRequest()
    const user = request.user

    // 用户必须满足指定的所有角色
    const hasRole = () =>
      roles.every((required) => user.roles.includes(required))

    if (user?.roles && hasRole()) {
      return true
    }

    throw new ForbiddenException('无权访问')
  }
}
